<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>类型模板管理</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <link rel="stylesheet" href="../plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="../plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="../css/style.css">
	<script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>

    <link rel="stylesheet" href="../plugins/select2/select2.css" />
    <link rel="stylesheet" href="../plugins/select2/select2-bootstrap.css" />
    <script src="../plugins/select2/select2.min.js" type="text/javascript"></script>

	    <link rel="stylesheet" type="text/css" href="../bootstrap-table/dist/bootstrap-table.css"/>
	    <script type="text/javascript" src="../bootstrap-table/dist/bootstrap-table.js"></script>
	    <script type="text/javascript" src="../bootstrap-table/dist/locale/bootstrap-table-zh-CN.js"></script>

	    <script type="text/javascript" src="../bootstrap-dialog/dist/js/bootstrap-dialog.js"></script>
	    <link rel="stylesheet" type="text/css" href="../bootstrap-dialog/dist/css/bootstrap-dialog.css">

</head>

<body class="hold-transition skin-red sidebar-mini" >
  <!-- .box-body -->
                
                    <div class="box-header with-border">
                        <h3 class="box-title">商品类型模板管理</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-default" title="新建" data-toggle="modal" data-target="#editModal" ><i class="fa fa-file-o"></i> 新建</button>
                                        <button type="button" class="btn btn-default" title="删除"><i class="fa fa-trash-o"></i> 删除</button>
                                       
                                        <button type="button" class="btn btn-default" title="刷新" onclick="window.location.reload();"><i class="fa fa-refresh"></i> 刷新</button>
                                    </div>
                                </div>
                            </div>
                            <div class="box-tools pull-right">
                                <div class="has-feedback">
							                  分类模板名称：<input  >									
									<button class="btn btn-default">查询</button>                                    
                                </div>
                            </div>
                            <!--工具栏/-->

			                  <!--数据列表-->
			                  <table id="dataList" class="table table-bordered table-striped table-hover dataTable">

			                  </table>
			                  <!--数据列表/-->
                        </div>
                        <!-- 数据表格 /-->
                     </div>
                    <!-- /.box-body -->

  <!-- 编辑窗口 -->
  <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" >
  	<div class="modal-content">
  		<div class="modal-header">
  			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
  			<h3 id="myModalLabel">商品类型模板编辑</h3>
  		</div>
  		<div class="modal-body">

  			<table class="table table-bordered table-striped"  width="800px" >
  		      	<tr>
  		      		<td>商品类型</td>
  		      		<td><input  class="form-control" placeholder="商品类型" id="specName" name="specName"> </td>
  		      	</tr>
  		      	<tr>
  		      		<td>关联品牌</td>
  		      		<td>
  		      			<select id="brand" multiple style="width: 100%">

  						</select>
  		      		</td>
  		      	</tr>
  		      	<tr>
  		      		<td>关联规格</td>
  		      		<td>
  						<select id="specification" multiple style="width: 100%">

  						</select>
  		      		</td>
  		      	</tr>

  		      	<tr>
  		      		<td>扩展属性</td>
  		      		<td>
  		      			<div class="btn-group">
                               <button type="button" class="btn btn-default" title="新增扩展属性" onclick="inser()"><i class="fa fa-file-o"></i> 新增扩展属性</button>

                          </div>
  						<table class="table table-bordered table-striped"  width="800px" id="productTable">
  							<thead>
  								<tr>
  								    <td><input type="checkbox" class="icheckbox_square-blue"></td>
  									<td>属性名称</td>
  									<td>操作</td>
  								</tr>
  							</thead>
  							<tbody>
  								<tr>
  									<td><input type="checkbox" class="icheckbox_square-blue" ></td>
  									<td><input class="form-control" placeholder="属性名称" ></td>
  									<td><button type="button" class="btn btn-default" title="删除" onclick="deletetr(this)"><i class="fa fa-trash-o"></i> 删除</button></td>
  								</tr>
  							</tbody>
  						</table>

  		      		</td>
  		      	</tr>

  			 </table>

  		</div>
  		<div class="modal-footer">
  			<button class="btn btn-success" data-dismiss="modal" aria-hidden="true" onclick="save()">保存</button>
  			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
  		</div>
  	  </div>
  	</div>
  </div>

  <!-- 修改 -->
   <div class="modal fade" id="editModals" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
     <div class="modal-dialog" >
   	<div class="modal-content">
   		<div class="modal-header">
   			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
   			<h3 id="myModalLabels">商品类型模板编辑</h3>
   		</div>
   		<div class="modal-body">

   			<table class="table table-bordered table-striped"  width="800px" >
   		      	<tr>
   		      		<td>商品类型</td>
   		      		<td><input  class="form-control" placeholder="商品类型" id="specNames" name="specNames"> </td>
   		      	</tr>
   		      	<tr>
   		      		<td>关联品牌</td>
   		      		<td>
   		      			<select id="brands" multiple style="width: 100%">

   						</select>
   		      		</td>
   		      	</tr>
   		      	<tr>
   		      		<td>关联规格</td>
   		      		<td>
   						<select id="specifications" multiple style="width: 100%">

   						</select>
   		      		</td>
   		      	</tr>

   		      	<tr>
   		      		<td>扩展属性</td>
   		      		<td>
   		      			<div class="btn-group">
                                <button type="button" class="btn btn-default" title="新增扩展属性" onclick="inser()"><i class="fa fa-file-o"></i> 新增扩展属性</button>

                           </div>
   						<table class="table table-bordered table-striped"  width="800px" id="productTables">
   							<thead>
   								<tr>
   								    <td><input type="checkbox" class="icheckbox_square-blue"></td>
   									<td>属性名称</td>
   									<td>操作</td>
   								</tr>
   							</thead>
   							<tbody id="tables">

   							</tbody>
   						</table>

   		      		</td>
   		      	</tr>

   			 </table>

   		</div>
   		<div class="modal-footer">
   			<button class="btn btn-success" data-dismiss="modal" aria-hidden="true" onclick="toupdata()">保存</button>
   			<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
   		</div>
   	  </div>
   	</div>
   </div>
</body>

</html>

<script>

	$(function () {
		getspecificationList();
		getBrandsList();
	})
	$(function(){
     $('#dataList').bootstrapTable({
         url: '/tbTypeTemplateController/gettbTypeTemplate',
		 method: 'post',//请求方式
		 contentType:"application/x-www-form-urlencoded",
		 striped: true,//是否显示行间隔色
		 cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		 pagination: true,//是否显示分页（*）
		 // sortOrder: "desc",//排序方式
		 //sortName:"mid",//排序字段
		 sidePagination: "server",//分页方式：client客户端分页，server服务端分页（*）
		 pageNumber: 1,//初始化加载第一页，默认第一页,并记录
		 pageSize: 3,//每页的记录行数（*）
		 pageList: [1, 3, 5],//可供选择的每页的行数（*）
		 //search: true,//是否显示表格搜索
		 // strictSearch: true,//严格搜索
		 showColumns: false,//是否显示所有的列（选择显示的列）
		 showRefresh: false,//是否显示刷新按钮
		 minimumCountColumns: 2,             //最少允许的列数
		 clickToSelect: true,                //是否启用点击选中行
		 uniqueId: "id",                     //每一行的唯一标识，一般为主键列
		 showToggle: false,                   //是否显示详细视图和列表视图的切换按钮
		 // cardView: true,                    //是否显示详细视图
		 detailView: true,                  //是否显示父子表
		 queryParams : function (params) {
			 //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
			 var temp = {
				 pageSize: params.limit,                         //每页条数
				 pageNum: (params.offset / params.limit) + 1,//当前页数
				 //模糊查询
				 cname : $('#rname').val(),
				 tid : $('[name=rid]').val()
			 };
			 return temp;
		 },
         columns: [{
             checkbox: true,
             visible: true                  //是否显示复选框
         }, {
             field: 'id',
             title: 'ID'
         }, {
             field: 'name',
             title: '模板名称名称'
         },{
			 field: 'specIds',
			 title: '关联规格',
			 formatter:function (value,row,index) {
				 var jsonspec = JSON.parse(value);
				 var specIds = "";
				 for (var a = 0;a < jsonspec.length;a++){
					 specIds += "," + jsonspec[a].text
				 }
				 return specIds.substr(1);
			 }
		 },{
			 field: 'brandIds',
			 title: '关联品牌',
			 formatter:function (value,row,index) {
				 var jsonbrand = JSON.parse(value);
				 var brandIds = "";
				 for (var b = 0;b < jsonbrand.length;b++){
					 brandIds += "," + jsonbrand[b].text
				 }
				 return brandIds.substr(1);
			 }
		 },{
			 field: 'customAttributeItems',
			 title: '自定义属性',
			 formatter:function (value,row,index) {
				 var Items = JSON.parse(value);
				 var ItemsIds = "";
				 for (var b = 0;b < Items.length;b++){
					 ItemsIds += "," + Items[b].text
				 }
				 return ItemsIds.substr(1);
			 }
		 }, {
             field: 'id',
             title: '操作',
             width: 120,
             align: 'center',
             valign: 'middle',
             formatter: function (value, row, index) {
                 var id = value;
                 var result = "";
                 result += '<button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModals" onclick="update(' + id + ')">修改</button>';
                 result += '<button type="button" class="btn bg-olive btn-xs" data-toggle="modal"  onclick="deletes(' + id + ')">删除</button>';
                 return result;
             }
         },]
     })
 })
	/*增加扩展属性*/
	function inser() {
	var table = document.getElementById("productTable");
	var tr = document.createElement("tr");
	tr.innerHTML = '<tr><td><input type="checkbox" class="icheckbox_square-blue" ></td><td><input class="form-control" placeholder="属性名称" ></td><td><button type="button" class="btn btn-default" title="删除" onclick="deletetr(this)"><i class="fa fa-trash-o"></i> 删除</button></td></tr>';
	table.appendChild(tr);
	}
	/*删除扩展属性*/
function deletetr(Obj) {
var tr = Obj.parentNode.parentNode;
tr.parentNode.removeChild(tr);
}

	function getBrandsList() {
		$.ajax({
			url:"/tbTypeTemplateController/selectBrand",
			type:"post",
			dataType:"json",
			success:function (parameter) {
				console.log(parameter)
				if(parameter.code == 100){
					var option = "";
					var list = parameter.data;
					for (var i = 0;i < list.length; i++){
						option += '<option value="'+list[i].id+'">'
						option += list[i].name;
						option += '</option >'
					}
					$("#brand").html(option);
					$("#brand").select2();
					$("#brands").html(option);
					$("#brands").select2();
				}
			},
			error:function () {
				alert("代码错误")
			}
		})
	}

	function getspecificationList() {
		$.ajax({
			url:"/tbTypeTemplateController/selectSpec",
			type:"post",
			dataType:"json",
			success:function (tablea) {
				var list = tablea.data
					var option = "";
					for (var i = 0;i < list.length; i++){
						option += '<option value="'+list[i].id+'">'
						option += list[i].specName;
						option += '</option >'
					}
					$("#specification").html(option);
					$("#specification").select2();
				$("#specifications").html(option);
				$("#specifications").select2();
			},
			error:function () {
				alert("代码错误")
			}
		})
	}

	/*zengjia*/
	function save() {
		var brands = $("#brand").select2('data');
		var specifications = $("#specification").select2('data');
		var tab = $("#productTable").find("tr");
		var brandarr= [];
		var specarrs = [];
		var productarrss = [];
		$.each(brands,function (i,e) {
			var json = {"id":e.id,"text":e.text}
			brandarr.push(json);
		})
		$.each(specifications,function (i,e) {
			var json = {"id":e.id,"text":e.text}
			specarrs.push(json);
		})
		for(var i = 1;i < tab.length;i++){
			var tds = $(tab[i]).find("td");
			var optionName = $(tds[1]).find("input").val();
			productarrss.push({"text":optionName})
		}
		//属性
		var optionsListJson = JSON.stringify(productarrss)
		//品牌
		var brandJson = JSON.stringify(brandarr);
		//规格
		var specJsons = JSON.stringify(specarrs);
		//商品类型
		var specNames = $("#specName").val();

		$.ajax({
			url:"/tbTypeTemplateController/toAdd",
			type:"post",
			data: {name:specNames,specIds:specJsons,brandIds:brandJson,customAttributeItems:optionsListJson},
			dataType:"json",
			success:function (list) {
				var str = list.data;
				if(str){
					alert("增加成功")
				}else{
					alert("增加失败")
				}

			},
			error:function () {
				alert("代码错误")
			}
		})
	}

	/*删除*/
	function deletes(id) {
		alert("删除方法"+id);
   		$.ajax({
   		    url:"/tbTypeTemplateController/delete?id="+id,
   		    type:"post",
   		    dataType:"json",
   		    success:function (parameter) {
   		        if(parameter){
   		            alert("删除成功")
			  getBrand();
   		        }else{
   		            alert("删除错误")
   		        }
   		    },
   		    error:function () {
   		        alert("代码错误")
   		    }
   		})
	}

	function update(id) {
		alert("修改方法"+id);
   		$.ajax({
   		    url:"/tbTypeTemplateController/updata?id="+id,
   		    type:"post",
   		    dataType:"json",
   		    success:function (parameter) {
				var template = parameter.data;
				alert(template.name)
				$("#specNames").val(template.name)
				var specIds = JSON.parse(template.specIds);
				var brandIds = JSON.parse(template.brandIds);
				/*规格*/
				var spec = [];
				/*品牌*/
				var brand = [];
				/*规格*/
				$.each(specIds,function (i,e) {
					spec.push(e.id)
				})
				$("#specifications").val(spec).trigger("change");
				/*品牌*/
				$.each(brandIds,function (i,e) {
					brand.push(e.id)
				})
				$("#brands").val(brand).trigger("change");

				/*属性回显*/
				var option = JSON.parse(template.customAttributeItems);
				var tr = "";
				for (var i = 0; i < option.length; i++){
					tr += "<tr>";
					tr += '<td><input type="checkbox" value="' + template.id + '" id="ids" name="ids"></td>';
					tr += "<td>";
					tr += "<input type='text' class='form-control' name='optionName' value='" + option[i].text + "' placeholder='属性名称'>";
					tr += "</td>";
					tr += "<td>";
					tr += "<button type='button'  class='btn btn-default' title='删除' onclick='deletetr(this)'><i class='fa fa-trash-o'></i>删除";
					tr += "</button>";
					tr += "</td>";
					tr += "</tr>";
				}
				$("#tables").html(tr);
   		    },
   		    error:function () {
   		        alert("代码错误")
   		    }
   		})
	}

	function toupdata() {
		var brands = $("#brands").select2('data');
		var specifications = $("#specifications").select2('data');
		var tab = $("#productTables").find("tr");
		var arr= [];
		var arrs = [];
		var arrss = [];
		$.each(brands,function (i,e) {
			var json = {"id":e.id,"text":e.text}
			arr.push(json);
		})
		$.each(specifications,function (i,e) {
			var json = {"id":e.id,"text":e.text}
			arrs.push(json);
		})
		for(var i = 1;i < tab.length;i++){
			var tds = $(tab[i]).find("td");
			var optionName = $(tds[1]).find("input").val();
			arrss.push({"text":optionName})
		}
		//属性
		var optionsListJson = JSON.stringify(arrss)
		//品牌
		var arrJson = JSON.stringify(arr);
		//规格
		var arrJsons = JSON.stringify(arrs);
		//商品类型
		var specNames = $("#specNames").val();

		var idss = $("#ids").val();

		$.ajax({
			url:"/tbTypeTemplateController/toupdata",
			type:"post",
			data: {id:idss,name:specNames,specIds:arrJsons,brandIds:arrJson,customAttributeItems:optionsListJson},
			dataType:"json",
			success:function (list) {
					alert("增加成功")
			},
			error:function () {
				alert("代码错误")
			}
		})
	}
</script>